package com.egao.go.biz.impl;

import com.egao.common.core.damon.constant.UserConstant;
import com.egao.common.core.damon.results.BaseDao;
import com.egao.common.core.damon.results.PageResult2;
import com.egao.common.core.damon.utils.Utils;
import com.egao.common.system.entity.User;
import com.egao.go.biz.DutchBiz;
import com.egao.go.entity.Dutch;
import com.egao.common.core.web.JsonResult;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;
import java.util.List;

/**
 *
 * 数据层实现类
 * @author : Doman
 * @date : 2020-09-21 10:28:24
 * @version ：1.0
 */
@Repository
public class DutchBizImpl extends BaseDao implements DutchBiz {

	@Override
	public JsonResult list(PageResult2<T> page, Dutch dutch, User loginUser) throws Exception {
		Map<String, String> map  = new HashMap<String, String>();
		RowMapper<Dutch> rm = new BeanPropertyRowMapper<Dutch>(Dutch.class);
		StringBuffer sql = new StringBuffer("select distinct d.id,d.organization_id,d.openid");
        sql.append(",d.title,d.content,d.groupTime,d.location");
		sql.append(",d.pic,d.endTime,d.end_person_num,d.total,d.type,d.state,d.examine");
		sql.append(",d.create_time,d.create_user,d.update_time,d.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.nick_name createName ");
        sql.append(",(select count(1) from go_dutch_user du where du.dutchId=d.id and du.deleted=0) personNum ");
        sql.append(" from go_dutch d ");
        sql.append(" inner join sys_user suser on suser.user_id=d.create_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=d.organization_id ");
		sql.append(" where d.deleted=0 and sogzn.deleted=0   ");
		sql.append(" and (exists (select 1 from  go_dutch_user du2 ");
		sql.append("  where instr(du2.openid,:openid)>0 and du2.dutchId=d.id and du2.deleted=0)");
		sql.append(" or instr(d.openid,:openid)>0 ) ");
		map.put("openid", loginUser.getXcxopenid());
		if(loginUser.getAdmin() !=null &&
			loginUser.getAdmin() != 1 && loginUser.getAdmin() != 2){
            sql.append(" and d.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
    	if(Utils.isNotEmpty(dutch)){
			if(Utils.isNotEmpty(dutch.getExamine())){
				sql.append(" and instr(d.examine,:examine)>0 ");
				map.put("examine", dutch.getExamine());
			}
			if(Utils.isNotEmpty(dutch.getSort())&&Utils.isNotEmpty(dutch.getOrder())){
                sql.append(" order by d."+dutch.getSort()+" "+dutch.getOrder());
            } else {
                sql.append(" order by d.create_time desc");
            }
		}
		return jsonResult(getPageQueryList(page, sql.toString(), map, rm));
	}

	@Override
	public JsonResult listExamine(PageResult2<T> page, Dutch dutch, User loginUser) throws Exception {
		Map<String, String> map  = new HashMap<String, String>();
		RowMapper<Dutch> rm = new BeanPropertyRowMapper<Dutch>(Dutch.class);
		StringBuffer sql = new StringBuffer("select distinct d.id,d.organization_id,d.openid");
        sql.append(",d.title,d.content,d.groupTime,d.location");
		sql.append(",d.pic,d.endTime,d.end_person_num,d.total,d.type,d.state,d.examine");
		sql.append(",d.create_time,d.create_user,d.update_time,d.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.nick_name createName ");
        sql.append(",(select count(1) from go_dutch_user du where du.dutchId=d.id and du.deleted=0) personNum ");
        sql.append(" from go_dutch d ");
        sql.append(" inner join sys_user suser on suser.user_id=d.create_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=d.organization_id ");
        sql.append(" where d.deleted=0 and sogzn.deleted=0 ");
		if(loginUser.getAdmin() != 1 && loginUser.getAdmin() != 2){
            sql.append(" and d.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
    	if(Utils.isNotEmpty(dutch)){
			if(Utils.isEmpty(dutch.getExamine())){
				sql.append(" order by d.examine desc,d.create_time desc");
			}
		}
		return jsonResult(getPageQueryList(page, sql.toString(), map, rm));
	}

	@Override
	public List<Dutch> list(Dutch dutch, User loginUser) {
		Map<String, String> map  = new HashMap<String, String>();
		RowMapper<Dutch> rm = new BeanPropertyRowMapper<Dutch>(Dutch.class);
        StringBuffer sql = new StringBuffer("select d.id,d.organization_id,d.openid");
        sql.append(",d.title,d.content,d.groupTime,d.location");
		sql.append(",d.pic,d.endTime,d.end_person_num,d.total,d.type,d.state,d.examine");
		sql.append(",d.create_time,d.create_user,d.update_time,d.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.nick_name createName ");
        sql.append(" from go_dutch d ");
        sql.append(" inner join sys_user suser on suser.user_id=d.create_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=d.organization_id ");
        sql.append(" where d.deleted=0 and sogzn.deleted=0 ");
		if(loginUser.getUserId() != UserConstant.ADMIN_ID){
            sql.append(" and d.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
    	if(Utils.isNotEmpty(dutch)){
//			if(Utils.isNotEmpty(dutch.getName())){
//				sql.append(" and instr(d.name,:name)>0 ");
//				map.put("name", dutch.getName());
//			}
            if(Utils.isNotEmpty(dutch.getSort())&&Utils.isNotEmpty(dutch.getOrder())){
				sql.append(" order by d."+dutch.getSort()+" "+dutch.getOrder());
			} else {
				sql.append(" order by d.create_time desc");
			}
		}
		getMapParameter(sql, map);
		return jdbcTemplate.query(sql.toString(),map, rm);
	}

	@Override
	public Integer unExamineNums(Dutch dutch, User loginUser) {
		Map<String, String> map  = new HashMap<String, String>();
        StringBuffer sql = new StringBuffer("select count(1) nums");
        sql.append(" from go_dutch d ");
        sql.append(" where d.deleted=0 ");
		if(Utils.isNotEmpty(dutch)){
			if(Utils.isNotEmpty(dutch.getExamine())){
				if(dutch.getExamine().equals("未审核")){
					sql.append(" and d.examine!='已审核'  ");
					map.put("examine", dutch.getExamine());
				} else {
					sql.append(" and d.examine='未通过'  ");
				}
			}
		}
		getMapParameter(sql, map);
		return jdbcTemplate.queryForObject(sql.toString(),map, Integer.class);
	}

	@Override
	public Dutch getById(Dutch dutch) {
		RowMapper<Dutch> rm = new BeanPropertyRowMapper<Dutch>(Dutch.class);
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql = new StringBuffer("select d.id,d.organization_id,d.openid");
        sql.append(",d.title,d.content,d.groupTime,d.location");
		sql.append(",d.pic,d.endTime,d.end_person_num,d.total,d.type,d.state,d.examine");
		sql.append(",d.create_time,d.create_user,d.update_time,d.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.nick_name createName ");
        sql.append(" from go_dutch d ");
        sql.append(" inner join sys_user suser on suser.user_id=d.create_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=d.organization_id ");
        sql.append(" where d.deleted=0 and sogzn.deleted=0 and d.id=:id ");
		map.put("id", dutch.getId());
		getMapParameter(sql, map);
		return jdbcTemplate.queryForObject(sql.toString(), map, rm);
	}

	@Override
	public Integer save(Dutch dutch, User loginUser) {
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql = new StringBuffer("select valnum");
		sql.append(" from go_settings d ");
		sql.append(" where type='examine' ");
		getMapParameter(sql, map);
		int examineNums = jdbcTemplate.queryForObject(sql.toString(), map, Integer.class);
		if(loginUser.getUserId()<examineNums){
			dutch.setExamine("已审核");
		}
		GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
		KeyHolder keyHolder=new GeneratedKeyHolder();
		sql =new StringBuffer("insert into go_dutch (");
		sql.append("organization_id,openid,title,content");
		sql.append(",groupTime,location,pic,endTime,end_person_num,examine");
		sql.append(",total,type,create_user,create_time) values ( ");
		sql.append(":organization_id,:openid,:title,:content");
		sql.append(",:groupTime,:location,:pic,:endTime,:end_person_num,:examine");
		sql.append(",:total,:type,:create_user,now())");
		map.put("organization_id", loginUser.getOrganizationId() + "");
		map.put("openid", loginUser.getXcxopenid());
		map.put("title", dutch.getTitle());
		map.put("content", dutch.getContent());
		map.put("groupTime", dutch.getGroupTime());
		map.put("location", dutch.getLocation());
		map.put("pic", dutch.getPic());
		map.put("endTime", dutch.getEndTime());
		map.put("end_person_num", dutch.getEndPersonNum());
		map.put("examine", dutch.getExamine());
		map.put("total", dutch.getTotal());
		map.put("type", dutch.getType());
		map.put("create_user", loginUser.getUserId() + "");
		getMapParameter(sql, map);
		int retVal = this.jdbcTemplate.update(sql.toString(), new SqlParameterSource() {
			@Override
			public boolean hasValue(String paramName) {
				return map.containsKey(paramName);
			}
			@Override
			public Object getValue(String paramName) throws IllegalArgumentException {
				return map.get(paramName);
			}
		}, generatedKeyHolder);

		Integer id = generatedKeyHolder.getKey().intValue();
		return id;
	}

	@Override
	public boolean update(Dutch dutch, User loginUser) {
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql =new StringBuffer("update go_dutch set ");
        sql.append("openid=:openid,title=:title,content=:content ");
		sql.append(",groupTime=:groupTime,location=:location,pic=:pic ");
		sql.append(",endTime=:endTime,end_person_num=:end_person_num,total=:total,type=:type ");
		sql.append(",update_time=now(),update_user=:update_user where id=:id ");
        map.put("openid", dutch.getOpenid());
        map.put("title", dutch.getTitle());
        map.put("content", dutch.getContent());
        map.put("groupTime", dutch.getGroupTime());
        map.put("location", dutch.getLocation());
        map.put("pic", dutch.getPic());
		map.put("endTime", dutch.getEndTime());
		map.put("end_person_num", dutch.getEndPersonNum());
        map.put("total", dutch.getTotal());
        map.put("type", dutch.getType());
		map.put("update_user", loginUser.getUserId() + "");
		map.put("id", dutch.getId());
		getMapParameter(sql, map);
		int count = jdbcTemplate.update(sql.toString(), map);
		return count > 0;
	}

	@Override
	public boolean updateState(Dutch dutch, User loginUser) {
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql =new StringBuffer("update go_dutch set ");
        sql.append("state=:state");
		sql.append(",update_time=now(),update_user=:update_user where id=:id ");
        map.put("state", dutch.getState());
		map.put("update_user", loginUser.getUserId() + "");
		map.put("id", dutch.getId());
		getMapParameter(sql, map);
		int count = jdbcTemplate.update(sql.toString(), map);
		return count > 0;
	}

	@Override
	public boolean updateExamine(Dutch dutch, User loginUser) {
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql =new StringBuffer("update go_dutch set ");
        sql.append("examine=:examine");
		sql.append(",update_time=now(),update_user=:update_user where id=:id ");
        map.put("examine", dutch.getExamine());
		map.put("update_user", loginUser.getUserId() + "");
		map.put("id", dutch.getId());
		getMapParameter(sql, map);
		int count = jdbcTemplate.update(sql.toString(), map);
		return count > 0;
	}

	@Override
	public boolean remove(Dutch dutch, User loginUser) {
		int count = 0;
		Map<String, String> map = null;
		if(dutch.getId().length()>0){
			for(String ID : dutch.getId().split(",")){
				map  = new HashMap<String, String>();
				if(ID==null || ID.equals("")){ break; }
				StringBuffer sql =new StringBuffer("update go_dutch set deleted=1" +
						",update_user=:update_user, update_time=now() "
						+ " where id =:id ");
				map.put("update_user", loginUser.getUserId() + "");
				map.put("id", ID);
				getMapParameter(sql, map);
				count = jdbcTemplate.update(sql.toString(),map);
			}
		}
		return count > 0;
	}
}
